package com.ly.weixmesg.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ly.weixmesg.dto.Weather;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LBG
 * @creat 2022-09-04-8:19
 */
public class WeatherUtils {

    private static String IPURL = "http://api.map.baidu.com/location/ip?ak={ak}";
    private static String WEATHERURL = "http://api.map.baidu.com/weather/v1/?district_id={district_id}&data_type={data_type}&ak={ak}";




    public static Weather getWeather(){
        RestTemplate restTemplate = new RestTemplate();
        Map<String,String> map = new HashMap<String,String>();
        map.put("district_id","330782"); // 地方行政代码
        map.put("data_type","all");//这个是数据类型
        map.put("ak","0I1FOoe19HjrHxYcE1WoZWauXIBloaDn");//应用ak
//        https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll //GET请求
//        map.put("ak","GdKxP7aGnWdwqNymueZu9TO8PYSPgAxZ");
        String res = restTemplate.getForObject(WEATHERURL, String.class, map);
        JSONObject json = JSONObject.parseObject(res);
        JSONArray forecasts = json.getJSONObject("result").getJSONArray("forecasts");
        List<Weather> weathers = forecasts.toJavaList(Weather.class);
        JSONObject now = json.getJSONObject("result").getJSONObject("now");
        Weather weather = weathers.get(0);
        weather.setText_now(now.getString("text"));
        weather.setTemp(now.getString("temp"));
        weather.setWind_class(now.getString("wind_class"));
        weather.setWind_dir(now.getString("wind_dir"));
        return weather;
    }

}
